<?php

class Skjb_Controller_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
    private $_auth;

    private $_acl;

    private $_noauth = array(
        'controller' => 'index',
        'action'     => 'login',
    );

    private $_noacl = array(
        'controller'  => 'index',
        'action'      => 'denied',
    );

    public function __construct(Zend_Acl $acl)
    {
        $this->_auth = Zend_Auth::getInstance();
        $this->_acl = $acl;
    }

    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $controller = $this->_request->controller;
        $action = $this->_request->action;
        $resource = $controller;

        if ($this->_auth->hasIdentity()) {
            $identity = $this->_auth->getIdentity();
            $role = $identity->role;
        } else {
            $role = 'guest';
        }

        if (!$this->_acl->has($resource)) {
            return;
        }
        
        $aclResource = $this->_acl->get($resource);
        if (!$this->_acl->isAllowed($role, $resource, $action)) {
            if (!$this->_auth->hasIdentity()) {
                if (isset($aclResource->noAuth)) {
                    $controller = $aclResource->noAuth['controller'];
                    $action = $aclResource->noAuth['action'];
                } else {
                    $controller = $this->_noauth['controller'];
                    $action = $this->_noauth['action'];
                }
            } else {
                if (isset($aclResource->noAcl)) {
                    $controller = $aclResource->noAcl['controller'];
                    $action = $aclResource->noAcl['action'];
                } else {
                    $controller = $this->_noacl['controller'];
                    $action = $this->_noacl['action'];
                }
            }
        }

        $this->_request->setControllerName($controller)
            ->setActionName($action)
            ->setDispatched(true);
    }
}